package com.example.linearlayoutdemo;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BookActivity extends AppCompatActivity {
    private EditText etBookNumber, etBookName;
    private Button btnAdd, btnDelete, btnUpdate, btnQuery, btnBack;
    private RecyclerView rvBookList;
    private BookAdapter bookAdapter;
    private String CURRENT_USER_ID; // 当前登录用户ID
    private BookViewModel bookViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book);
        Bundle bundle = getIntent().getExtras();
        String email = bundle.getString("email");
        CURRENT_USER_ID = email;

        // 初始化视图
        initViews();
        //初始化ViewModel
        initViewModel();
        // 初始化列表
        initRecyclerView();

        // 首次进入查询所有书籍
        queryBooks("");
    }

    private void initViews() {
        etBookNumber = findViewById(R.id.et_book_number);
        etBookName = findViewById(R.id.et_book_name);
        btnAdd = findViewById(R.id.btn_add);
        btnDelete = findViewById(R.id.btn_delete);
        btnUpdate = findViewById(R.id.btn_update);
        btnQuery = findViewById(R.id.btn_query);
        btnBack = findViewById(R.id.btn_back);

        // 按钮点击事件（直接在Activity中处理数据库操作）
        btnAdd.setOnClickListener(v -> addBook());
        btnDelete.setOnClickListener(v -> deleteBook());
        btnUpdate.setOnClickListener(v -> updateBook());
        btnQuery.setOnClickListener(v -> queryBooks(etBookNumber.getText().toString().trim()));
        btnBack.setOnClickListener(v -> finish());
    }
    // 2. 初始化ViewModel
    private void initViewModel() {
        bookViewModel = new ViewModelProvider(this).get(BookViewModel.class);
        bookViewModel.init(this); // 初始化数据库Helper

        // 观察书籍列表变化：数据更新时，刷新适配器
        bookViewModel.bookList.observe(this, books -> {
            bookAdapter.setBookList(books);
            Toast.makeText(BookActivity.this, "共" + (books == null ? 0 : books.size()) + "本图书", Toast.LENGTH_SHORT).show();
        });
        bookViewModel.getOperationResult().observe(this, new Observer<OperationResult>() {
            @Override
            public void onChanged(OperationResult operationResult) {
                if(operationResult != null)
                    Toast.makeText(BookActivity.this, operationResult.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void initRecyclerView() {
        rvBookList = findViewById(R.id.rv_book_list);
        rvBookList.setLayoutManager(new LinearLayoutManager(this));
        bookAdapter = new BookAdapter();
        rvBookList.setAdapter(bookAdapter);

        // 列表项点击：回填数据到输入框
        bookAdapter.setOnItemClickListener(book -> {
            etBookNumber.setText(book.getBookNumber());
            etBookName.setText(book.getBookName());
        });
    }

    // 添加书籍（直接调用dbHelper，在子线程执行）
    private void addBook() {
        String bookNumber = etBookNumber.getText().toString().trim();
        String bookName = etBookName.getText().toString().trim();

        if (bookNumber.isEmpty() || bookName.isEmpty()) {
            Toast.makeText(this, "书号和书名不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        bookViewModel.addBook(new Book(bookNumber, bookName, CURRENT_USER_ID));
//        if (result != -1) {
//            Toast.makeText(BookActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
//            queryBooks(""); // 刷新列表
//            clearEditTexts();
//        } else {
//            Toast.makeText(BookActivity.this, "添加失败（书号可能重复）", Toast.LENGTH_SHORT).show();
//        }
    }

    // 删除书籍
    private void deleteBook() {
        String bookNumber = etBookNumber.getText().toString().trim();
        if (bookNumber.isEmpty()) {
            Toast.makeText(this, "请输入要删除的书号", Toast.LENGTH_SHORT).show();
            return;
        }
        bookViewModel.deleteBook(bookNumber, CURRENT_USER_ID);
//        if (rowsDeleted > 0) {
//            Toast.makeText(BookActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
//            queryBooks("");
//            clearEditTexts();
//        } else {
//            Toast.makeText(BookActivity.this, "删除失败（书号不存在）", Toast.LENGTH_SHORT).show();
//        }
    }

    // 更新书籍
    private void updateBook() {
        String bookNumber = etBookNumber.getText().toString().trim();
        String newBookName = etBookName.getText().toString().trim();

        if (bookNumber.isEmpty() || newBookName.isEmpty()) {
            Toast.makeText(this, "书号和新书名不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        bookViewModel.updateBook(bookNumber, newBookName, CURRENT_USER_ID);
//        if (rowsUpdated > 0) {
//            Toast.makeText(BookActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
//            queryBooks("");
//            clearEditTexts();
//        } else {
//            Toast.makeText(BookActivity.this, "修改失败（书号不存在）", Toast.LENGTH_SHORT).show();
//        }
    }

    // 查询书籍
    private void queryBooks(String bookNumber) {
        bookViewModel.queryBooks(bookNumber, CURRENT_USER_ID);
    }

    private void clearEditTexts() {
        etBookNumber.setText("");
        etBookName.setText("");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}
    